<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Dart语言基础之Map》 - 飞雪无情的博客</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Java、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Dart语言基础之Map》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.flysnow.org/posts/flutter/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BMap/" />
<meta property="article:published_time" content="2021-03-29T19:18:14+08:00" />
<meta property="article:modified_time" content="2021-03-29T19:18:14+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Dart语言基础之Map》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="飞雪无情的博客">
<meta name="apple-mobile-web-app-title" content="飞雪无情的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://www.flysnow.org/posts/flutter/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BMap/" /><link rel="prev" href="https://www.flysnow.org/posts/flutter/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BData/" /><link rel="next" href="https://www.flysnow.org/posts/flutter/%E5%9C%A8Flutter%E4%B8%AD%E5%88%B6%E4%BD%9C%E5%A4%96%E5%8D%96%E5%BA%94%E7%94%A8/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Dart语言基础之Map》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/www.flysnow.org\/posts\/flutter\/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BMap\/"
        },"genre": "posts","keywords": "flutter","wordcount":  1132 ,
        "url": "https:\/\/www.flysnow.org\/posts\/flutter\/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BMap\/","datePublished": "2021-03-29T19:18:14+08:00","dateModified": "2021-03-29T19:18:14+08:00","publisher": {
            "@type": "Organization",
            "name": "飞雪无情"},"author": {
                "@type": "Person",
                "name": "飞雪无情"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">飞雪无情的博客</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/tools/">工具</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/archives/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Dart语言基础之Map》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>飞雪无情</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-03-29">2021-03-29</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;1132 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;3 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#map定义">Map定义</a>
      <ul>
        <li><a href="#不指定泛型">不指定泛型</a></li>
        <li><a href="#指定泛型">指定泛型</a></li>
      </ul>
    </li>
    <li><a href="#map常见属性">Map常见属性</a></li>
    <li><a href="#map常见方法">Map常见方法</a></li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<h2 id="map定义">Map定义</h2>
<h3 id="不指定泛型">不指定泛型</h3>
<pre><code>  var map1 = {'aa': 'aaa', 'bb': 'bbb', 'cc': true}; //直接赋值初始值
  print(map1); //{aa: aaa, bb: bbb, cc: true}

  Map map2 = {'a': 'a1', 'b': 'b1'}; //直接赋值初始值
  print(map2); //{a: a1, b: b1}

  map2['c'] = 'c1';
  print(map2); //{a: a1, b: b1, c: c1}

  var map3 = new Map();
  map3['a'] = 'a3';
  map3[2] = 'b3';
  print(map3); //{a: a3, 2: b3}
  print(map3[3]); //null 如果不存在，则为null
  map3[3] = null; //key存在 value存在 value的值为null
  print(map3); //{a: a3, 2: b3, 3: null}
  
</code></pre><h3 id="指定泛型">指定泛型</h3>
<pre><code>var map4 = &lt;String, String&gt;{};
  Map&lt;int, String&gt; map5 = new Map(); //new也可以省略
  map5[1] = 'a5';
  map5[2] = 'b5';
  print(map5); //{1: a5, 2: b5}

  Map&lt;String, int&gt; map6 = {'a6': 1, 'b6': 2};
  print(map6); //{a6: 1, b6: 2}
</code></pre><h2 id="map常见属性">Map常见属性</h2>
<pre><code> Map&lt;String, int&gt; map7 = Map();
  map7['a7'] = 1;
  map7['b7'] = 2;
  map7['c7'] = 3;
  print(map7.length); //3 长度
  print(map7.isNotEmpty); //true  是否不为空
  print(map7.isEmpty); //flase  是否为空
  print(
      '${map7.keys},${map7.keys.runtimeType}'); // (a7, b7, c7),_CompactIterable&lt;String&gt;    Map的所有key
  print(
      '${map7.values},${map7.values.runtimeType}'); //(1, 2, 3),_CompactIterable&lt;int&gt;    Map的所有value
  print(
      '${map7.entries},${map7.entries.runtimeType}'); // (MapEntry(a7: 1), MapEntry(b7: 2), MapEntry(c7: 3)),MappedIterable&lt;String, MapEntry&lt;String, int&gt; Map的所有键值对

</code></pre><h2 id="map常见方法">Map常见方法</h2>
<ul>
<li>新增一个键值对</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map8 = Map();
  map8['a8'] = 1;
  print(map8); //{a8: 1}
  
</code></pre><hr>
<ul>
<li>修改一个键值对</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map9 = {'a9': 1, 'b9': 2};
  map9['a9'] = 9;
  print(map9); //{a9: 9, b9: 2}  
  
</code></pre><hr>
<ul>
<li>update(K key, V update(V value), {V ifAbsent()})  根据指定的Key对应的value做出修改，同时Map本身也会被修改</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map10 = {'a10': 1, 'b10': 2, 'c10': 3};
  var resultMap10 = map10.update('b10', (value) =&gt; value * 2);
  print(resultMap10); //4
  print(map10); //{a10: 1, b10: 4, c10: 3}
  
  var resultMap101 = map10.update('c', (value) =&gt; (value * 2),
      ifAbsent: () =&gt; (10)); //如果key不存在，但是有ifAbsent参数，返回idAbsent函数的值，并添加到map中
  print('$resultMap101,${resultMap101.runtimeType}'); //10,int
  print(map10); //{a10: 1, b10: 4, c10: 3, c: 10}
 
</code></pre><hr>
<ul>
<li>updateAll(V update(K key, V value)) 根据参数内的函数，修改map</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map11 = {'a11': 2, 'b11': 3, 'c11': 4};
  var resultMap11 = map11.updateAll((key, value) {
    return value * 2;
  });
  print(map11); //{a11: 4, b11: 6, c11: 8}
  map11.updateAll((key, value) {
    if (key == 'a11') {
      return value * 2;
    }
    if (key == 'c11') {
      return value + 1;
    }
    return 7; //如果没有这行，b11对应的value为null 这里可以看出updateall会影响所有的键值对
  });
  print(map11); //{a11: 8, b11: 7, c11: 9}
  
</code></pre><hr>
<ul>
<li>remove() 删除一个key</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map12 = {'a12': 2, &quot;b12&quot;: 1};
  map12.remove('a12');
  print(map12); //{b12: 1}
  map12.remove('c12'); //删除一个不存在的key，毫无影响，无报错无警告
  print(map12); //{b12: 1}  
  
</code></pre><hr>
<ul>
<li>removeWhere(bool predicate(K key, V value))  根据函数条件批量删除key</li>
</ul>
<pre><code> Map&lt;String, int&gt; map13 = {'a13': 3, 'b13': 4, 'c13': 1};
 map13.removeWhere((key, value) =&gt; value &gt; 3);
 print(map13); //{a13: 3, c13: 1}  
 
</code></pre><hr>
<ul>
<li>containsKey() 是否包含某个key  contrainsValue()是否包含某个value</li>
</ul>
<pre><code>   Map&lt;String ,int&gt; map14 = {'a14':1};
   bool resultMap14 = map14.containsKey('a11'); //false
   bool resultMap141 = map14.containsValue(1); //true
</code></pre><hr>
<ul>
<li>forEach(void f(K key, V value)) 遍历Map ,遍历时不可add或者remove</li>
</ul>
<pre><code>  Map&lt;String, int&gt; map15 = {'a15': 1, 'b15': 2, 'c': 3, 'd': 4, 'e': 5};
  map15.forEach((key, value) {
    print('$key,$value');
    /*
    a15,1
    b15,2
     c,3
     d,4
     e,5
    */
  });
   map15.forEach((key, value) {
    //  if(key == 'a15'){value = 8;}
    map15['a15'] = 8;
   });
   print(map15); //{a15: 8, b15: 2, c: 3, d: 4, e: 5}
   
</code></pre><hr>
<ul>
<li>map() 遍历每个键值对 根据参数函数，对keyvalue做出修改，转换成其他泛型Map</li>
</ul>
<pre><code>   Map&lt;String,int&gt; map16 = {'a16':7,&quot;b16&quot;:5,'c16':4};
   Map&lt;int,String&gt; map17 = map16.map((key, value) {
       return MapEntry(value, key);
   });
   print(map17);
   
</code></pre><hr>
<ul>
<li>addAll() 两个Map合并，类型需要一致 ，且如果key相同，则会覆盖value</li>
</ul>
<pre><code>  Map&lt;String,int&gt; map18 = {'a18':1,'b18':7,'a19':2};
  Map&lt;String,int&gt; map19 = {'a19':9};
  map18.addAll(map19);
  print(map18); //{a18: 1, b18: 7, a19: 9}   
  
</code></pre><hr>
<ul>
<li>addEntres(key,value)  两个Map合并，类型需要一致 ，且如果key相同，则会覆盖value</li>
</ul>
<pre><code>  Map&lt;String,int&gt; map20 = {'a20':2,'b20':3};
  Map&lt;String,int&gt; map21 = {'a21':5,'b21':9};
  map20.addEntries(map21.entries);
  print(map20); //{a20: 2, b20: 3, a21: 5, b21: 9}  
  
</code></pre><ul>
<li>putIfAbsent()  存在key则返回value，查不到则返回值 不修改Map</li>
</ul>
<pre><code> Map&lt;String,int&gt; map22 = {'a22':3,'b22':4};
 var resultMap22 = map22.putIfAbsent('a22', () =&gt; 2); //存在key则返回value，查不到则返回 2 不修改Map
 print('$resultMap22,$map22');//3,{a22: 3, b22: 4} 
 
 var resultMap221 = map2.putIfAbsent('a2', () =&gt; 1);
 print('$resultMap221,$map22'); //1,{a22: 3, b22: 4} //存在key则返回value，查不到则返回 1 不修改Map 
 
</code></pre><hr>
<ul>
<li>cast() 泛型提升为其父祖类</li>
</ul>
<pre><code> Map&lt;String,int&gt; map23 = {'a33':3};
 Map&lt;Object,Object&gt; map24 = map23.cast();
 print('$map23,${map23.runtimeType},$map24,${map24.runtimeType}'); //{a33: 3},_InternalLinkedHashMap&lt;String, int&gt;,{a33: 3},CastMap&lt;String, int, Object, Object&gt;

</code></pre><hr>
<ul>
<li>清除所有键值对，对所有类型map都适用</li>
</ul>
<pre><code> Map&lt;String,int&gt; map25 = {'a25':2,'b25':3};
 map25.clear();
 print('$map25,${map25.runtimeType}'); //{},_InternalLinkedHashMap&lt;String, int&gt;
</code></pre></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-03-29</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/dart%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80%E4%B9%8BData/" class="prev" rel="prev" title="《Dart语言基础之Data》"><i class="fas fa-angle-left fa-fw"></i>《Dart语言基础之Data》</a>
            <a href="/posts/flutter/%E5%9C%A8Flutter%E4%B8%AD%E5%88%B6%E4%BD%9C%E5%A4%96%E5%8D%96%E5%BA%94%E7%94%A8/" class="next" rel="next" title="《在Flutter中制作外卖应用》">《在Flutter中制作外卖应用》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">飞雪无情</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
